<?php

namespace app\index\behavior;

use app\common\facade\CategoryFacade;
use app\common\model\UrlModel;

class UrlBehavior
{
    public function run()
    {
        $url = request()->pathinfo();

        $url = '/' . ltrim($url, '/');
        if (preg_match('/^\/(task|admin|vue|api|index)(\/)?/', $url)) {
            return;
        }

        $newUrl = UrlModel::fullUrl($url);

        $topCategory = CategoryFacade::findCategoryByAttr('is_top', 1);
        if (!empty($topCategory) && $url != '/' . $topCategory['name'] && strpos($url, '/' . $topCategory['name'] . '/') !== 0) {
            $subNames = CategoryFacade::getSubCateNames($topCategory['id'], true, false);
            if (!empty($subNames)) {
                if (preg_match('/^\/(' . implode('|', $subNames) . ')(\/|$)/', $newUrl)) {
                    $newUrl = '/' . $topCategory['name'] . $newUrl;
                }
            }
        }

        if ($url != $newUrl) {
            request()->setPathinfo(ltrim($newUrl, '/'));
        }
    }
}
